﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Rung.Soft.Jx3Tookit.Business.Addon
{
    public static class AddonLoader
    {
        private static MainForm mainForm;
        private static string addonFolder;
        public static SortedList<int, IAddon> Addons;

        public static void Init(string folder, MainForm form)
        {
            addonFolder = folder;
            mainForm = form;
            Addons = new SortedList<int, IAddon>();
        }

        public static void Load()
        {
            DirectoryInfo di = new DirectoryInfo(addonFolder);
            foreach (FileInfo file in di.GetFiles())
            {
                if (file.Extension != ".dll") continue;

                Assembly a = Assembly.LoadFrom(file.FullName);
                foreach (Type t in a.GetTypes())
                {
                    if (t.GetInterfaces().Contains(typeof(IAddon)))// t 继承自 IAddon 接口。
                    {
                        //// 实例化一个 t.Control 对象。
                        //PropertyInfo pi = t.GetProperty("Control");
                        //ControlBase cb = pi.PropertyType.BaseType.GetConstructor(new Type[0]).Invoke(null) as ControlBase;
                        //// 以 cb 为参数，实例化一个 t 对象。
                        ////IAddon addon = t.GetConstructor(new Type[1] { typeof(ControlBase) }).Invoke(new object[] { cb }) as IAddon;
                        IAddon addon = t.GetConstructor(new Type[] { typeof(MainForm) }).Invoke(new object[] { AddonLoader.mainForm }) as IAddon;

                        if (Addons.ContainsKey(addon.Order))
                        {
                            Addons.RemoveAt(addon.Order);
                        }
                        Addons.Add(addon.Order, addon);
                    }
                }
            }

            foreach (var addon in Addons)
            {
                mainForm.tabMain.TabPages.Add(addon.Value.TabPage);
                addon.Value.Load();
            }
        }
    }
}
